package com.cc.springboot_test.redis;

import com.cc.springboot_test.converter.ObjectConverter;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    private static final Logger logger = LoggerFactory.getLogger(RedisService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ObjectConverter objectConverter;

    // 获取缓存，此方法不支持Character类型
    public <T> T getValue(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return (T) redisTemplate.boundValueOps(key).get();
    }

    // 将对象写入缓存
    public <T> void setValue(String key, T value) {
        setValue(key, value, -1);
    }

    // 将value对象写入缓存，包含失效时间（秒）
    public <T> void setValue(String key, T value, long timeout) {
        if (StringUtils.isBlank(key)) {
            logger.error("设置Redis值业务，KEY为空，key={}，value={}，timeout={}", key, value, timeout);
            throw new RuntimeException("设置的Redis值业务，KEY为空！");
        }

        if (value == null) {
            logger.error("设置Redis值业务，VALUE为空，key={}，value={}，timeout={}\", key, value, timeout");
            throw new RuntimeException("设置的Redis值业务，VALUE为空！");
        }

        redisTemplate.opsForValue().set(key, value);
        if (timeout > 0) {
            redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
    }

    // 获取缓存json对象
    public <T> T getFormJson(String key, Class<T> clazz) {
        String value = getValue(key);
        if (StringUtils.isBlank(value)) {
            return null;
        }

        try {
            T readValue = objectConverter.readValue(value, clazz);
            return readValue;
        } catch (IOException e) {
            throw new RuntimeException("读取Redis JSON串异常！", e);
        }
    }

    // 将value对象以JSON格式写入缓存
    public void setJson(String key, Object value) {
        setJson(key, value, -1);
    }

    // 将value对象以JSON格式写入缓存，包含失效时间（秒）
    public <T> void setJson(String key, T value, long timeout) {
        if (StringUtils.isBlank(key)) {
            logger.error("设置Redis值业务，KEY为空，key={}，value={}，timeout={}", key, value, timeout);
            throw new RuntimeException("设置的Redis值业务，KEY为空！");
        }

        if (value == null) {
            logger.error("设置Redis值业务，VALUE为空，key={}，value={}，timeout={}\", key, value, timeout");
            throw new RuntimeException("设置的Redis值业务，VALUE为空！");
        }

        try {
            String json = objectConverter.writeValueAsString(value);
            redisTemplate.opsForValue().set(key, json);
            if (timeout > 0) {
                redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("将VALUE对象以JSON格式写入缓存失败！");
        }
    }

    // 根据keys精确匹配删除缓存
    public void delete(String... keys) {
        if (ArrayUtils.isEmpty(keys)) {
            throw new RuntimeException("根据keys精确匹配删除缓存，KEYS为空");
        }

        if (keys.length == 1) {
            redisTemplate.delete(keys[0]);
        } else {
            redisTemplate.delete(CollectionUtils.arrayToList(keys));
        }
    }
}
